package com.yjyw.tiexie.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.yjyw.tiexie.adapter.DoubleDefault0Adapter;
import com.yjyw.tiexie.adapter.IntegerDefault0Adapter;
import com.yjyw.tiexie.adapter.LongDefault0Adapter;
import com.yjyw.tiexie.adapter.StringDefault0Adapter;

import java.lang.reflect.Type;

/**
 * Created on 2019/7/23.
 *
 * @author ${AUTHOR}
 * TODO:
 */
public class GsonUtil {
    /**
     * bean转换为json
     * @return
     */
    public static String getJson(Object src) {
        return new Gson().toJson(src);
    }

    /**
     * json转换为bean
     *
     * @param json
     * @param c
     * @return
     */
    public static Object getObject(String json, Class c) {
        Gson gson = new GsonBuilder().registerTypeAdapter(Integer.class, new IntegerDefault0Adapter())
                .registerTypeAdapter(int.class, new IntegerDefault0Adapter())
                .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                .registerTypeAdapter(Long.class, new LongDefault0Adapter())
                .registerTypeAdapter(long.class, new LongDefault0Adapter())
                .registerTypeAdapter(String.class, new StringDefault0Adapter())
                .create();
        return gson.fromJson(json, c);
    }

    public static <T> T fromJson(String json, Type type) {
        Gson gson = new GsonBuilder().registerTypeAdapter(Integer.class, new IntegerDefault0Adapter())
                .registerTypeAdapter(int.class, new IntegerDefault0Adapter())
                .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                .registerTypeAdapter(Long.class, new LongDefault0Adapter())
                .registerTypeAdapter(long.class, new LongDefault0Adapter())
                .registerTypeAdapter(String.class, new StringDefault0Adapter())
                .create();
        // JsonSyntaxException
        return gson.fromJson(json, type);
    }
}
